package com.sskj.mqtt.many;

import java.util.regex.Pattern;

/**
 * @Author: Like
 * @Date: 2025/3/3 15:40
 * @Description: 匹配主题
 */
public class TopicPattern {
    private final Pattern pattern;
    private final String originalFilter;

    public TopicPattern(String filter) {
        this.originalFilter = filter;
        this.pattern = compileFilter(filter);
    }

    private static Pattern compileFilter(String filter) {
        String regex = filter
                .replaceAll("\\+", "[^/]+")
                .replaceAll("/#", "(/.*)?");
        return Pattern.compile("^" + regex + "$");
    }

    public boolean matches(String topic) {
        return pattern.matcher(topic).matches();
    }

    public String getOriginalFilter() {
        return originalFilter;
    }
}
